package com.qxp.simplerpc.registry;

import com.qxp.simplerpc.RegistryService;
import com.qxp.simplerpc.entity.CommonProperties;
import com.qxp.simplerpc.exception.RpcException;
import com.qxp.simplerpc.server.RpcServer;
import com.qxp.simplerpc.utils.SimpleRpcProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
public class Register {
    private ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void register() {
        RegistryService registryService = this.applicationContext.getBean(RegistryService.class);
        registryCheck(registryService);
        SimpleRpcProperties simpleRpcProperties = this.applicationContext.getBean(SimpleRpcProperties.class);
        RpcServer rpcServer = this.applicationContext.getBean(RpcServer.class);
        new Thread(rpcServer).start();
        CommonProperties commonProperties = new CommonProperties(simpleRpcProperties.getHost(), simpleRpcProperties.getPort());
        registryService.register(commonProperties.toString());
    }

    private void registryCheck(RegistryService registryService){
        if (Objects.isNull(registryService)) {
            throw new RpcException("RegistryService instance can't be null...please check again...");
        }
    }
}
